<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\services\user;

use app\jobs\notice\SmsJob;
use app\model\user\User;
use app\model\user\UserBill;
use app\model\user\UserShareInviteLog;
use app\model\v1\recovery\ConfigActivity;
use app\model\v1\recovery\RecoveryProduct;
use app\services\BaseServices;
use app\dao\user\UserDao;
use app\services\message\sms\SmsRecordServices;
use app\services\order\store\PushMsgServices;
use app\services\wechat\WechatUserServices;
use crmeb\services\CacheService;
use think\exception\ValidateException;
use think\facade\Config;

/**
 *
 * Class LoginServices
 * @package app\services\user
 * @mixin UserDao
 */
class LoginServices extends BaseServices
{

    /**
     * LoginServices constructor.
     * @param UserDao $dao
     */
    public function __construct(UserDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * H5账号登陆
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login($account, $password, $spread_uid, $device_token_an='', $device_token_ios='', $isApp=0, $is_from,$client,$user_type)
    {

        $user = $this->dao->getOne(['phone' => $account], '*'); //uid,pwd,status
        if ($user) {
            if ($user->pwd !== md5((string)$password))
                throw new ValidateException('账号或密码错误');
            if ($user->pwd === md5('123456'))
                throw new ValidateException('请修改您的初始密码，再尝试登录！');
        } else {
            throw new ValidateException('账号或密码错误');
        }
        if (!$user['status'])
            throw new ValidateException('已被禁止，请联系管理员');


        $sur_day = 0;
        $lasted = 0;  //过期后的第一天, 返回数据字段，前端提示会员过期文案
        if(!empty($user['overdue_time'])) {
            if($user['overdue_time'] > time()) {
                $sur_time = $user['overdue_time'] - time();
                if ($sur_time <= 86400) $sur_day = 1;
                if ($sur_time >= 86400 && $sur_time <= 172800) $sur_day = 2;
                if ($sur_time >= 172800 && $sur_time <= 86400) $sur_day = 3;
            }
            if($user['overdue_time'] < time()) {
                if( (time() - $user['overdue_time']) <= 3600*24){
                    $lasted = 1;
                }
            }
        }


        $is_from = false;
        //----------------------------新人礼分享者人数、积分更新--------------------------
        //注册送积分，用户从app登录后
        $is_app_login = 2;
        $share_pid = 0;
        if($isApp){
            $is_app_login = 1;
            $integral = 0;
            $share_ids = [];
            $share_id_count = 0;

            if($user['monitor_sanlitun'] == 1) $is_from = true;
            if($is_from){
                if(!empty($user['spread_uid']) &&  ($user['is_app_login']==2) ){
                    $code_find = $this->dao->getOne(['uid' => $user['spread_uid']]);
                    if(!empty($code_find)){
                        $share_pid = $code_find->uid; //分享者id
                        $integral = $code_find->integral ?? 0;
                        $share_id_count = $code_find->subordinate_count; //ids数量
                        if(!empty($code_find->subordinate)) $share_ids = explode(',', $code_find->subordinate ?? ''); //ids
                    }
                }
            }
        }
        //--------------------------------------------------------------------


		$uid = (int)$user['uid'];
        //更新用户信息
        //更新用户信息
        if(!empty($device_token_an)) $user['device_token_an'] = $device_token_an;
        if(!empty($device_token_ios)) $user['device_token_ios'] = $device_token_ios;
        if(!empty($client)) $user['client_type'] = $client;
        if(!empty($user_type)) $user['user_type'] = $user_type;
        if($is_app_login == 1) $user['is_app_login'] = $is_app_login;

        $token = $this->createToken($uid, 'api', $user->pwd);
        if ($token) {
            // 用户登录成功事件
                $this->updateUserInfo($uid, ['spread_uid' => $spread_uid], $user);
			// 用户登录成功事件
			event('user.login', [$uid, app('request')->ip()]);


            //----------------------------分享者人数、积分更新--------------------------
            if(!empty($share_pid)){
                array_push($share_ids, $uid);
                $subordinate = implode(',', $share_ids);
                $update = [
                    'subordinate' => $subordinate,
                    'integral' => $integral+User::SHARE_NEW_INTEGRAL,
                    'subordinate_count' => $share_id_count+1,
                ];
                User::where("uid", $share_pid)->update($update);

                //分享邀请记录添加
                UserShareInviteLog::addUserShareInvateLog($share_pid,1,User::SHARE_NEW_INTEGRAL, $uid);

                $add = [
                    'uid' => $share_pid,
                    'pm' => 1,
                    'title' => '分享新用户注册赠送积分',
                    'category' => 'integral',
                    'type' => 'share_new',
                    'number' => User::SHARE_NEW_INTEGRAL,
                    'balance' => $integral+User::SHARE_NEW_INTEGRAL,
                    'mark' => '分享新用户注册赠送'.User::SHARE_NEW_INTEGRAL.'积分',
                    'add_time' => time(),
                ];
                UserBill::create($add);

                //友盟系统消息
	            /** @var PushMsgServices $pushMsgServices */
                $pushMsgServices = app()->make(PushMsgServices::class);
                $pushMsgServices->umengPushMsg($share_pid, '', 5, (string)User::SHARE_NEW_INTEGRAL);
            }
            //--------------------------------------------------------------------



            return ['token' => $token['token'], 'uid' => $uid, 'expires_time' => $token['params']['exp'], 'sur_day' => $sur_day, 'lasted'=>$lasted];
        } else
            throw new ValidateException('登录失败');
    }


    public function actNewUserInte($params = [])
    {
//        $uid_find = $this->dao->getOne(['uid' => $params['user_id']]);
//        $integral = $uid_find->integral ?? 0;
//
//        $number_inte = ConfigActivity::getIntegralNumberValue($params["client_type"]);
//        $number_inte = $number_inte ? $number_inte : 0;

        $update = [
            'is_register_inte' => 1,
//            'integral' => $integral + $number_inte, //User::NEW_REGISTER_INTEGRAL,
        ];
        $res = User::where("uid", $params['user_id'])->update($update);


//        $add = [
//            'uid' => $params['user_id'],
//            'pm' => 1,
//            'title' => '新用户注册赠送积分',
//            'category' => 'integral',
//            'type' => 'new_register',
//            'number' => $number_inte,     //User::NEW_REGISTER_INTEGRAL,
//            'balance' => $integral + $number_inte,  //User::NEW_REGISTER_INTEGRAL,
//            'mark' => '新用户注册赠送' . $number_inte . '积分',    //User::NEW_REGISTER_INTEGRAL
//            'add_time' => time(),
//        ];
//        UserBill::create($add);

        return true;
    }




    public function actNewUserMember($params = [])
    {
        //------------------------新人礼--------------------------
//        $data['overdue_time'] = time() + 3600 * 24 * 30;
//        $data['is_money_level'] = 1;
//        $data['level_status'] = 1;
//        $data['inter_reg'] = 1;

        $activity_find = ConfigActivity::where("client_type", $params["client_type"])->where("end_time",'>',time())->where("start_time",'<',time())->where("type", 2)->find() ?? [];
        if (!$activity_find){
            return false;
        }

        $time  =3600 * 24 * $activity_find['vip_day'] ?? 30 ;

        //-------------------------------------------------------

        $overdue_time = User::where("uid", $params['user_id'])->value('overdue_time');


        if ($overdue_time>time()){
            $update = [
                'is_register_member' => 1,
                'is_money_level' => 1,
                'level_status' => 1,
                'inter_reg' => 1,
                'overdue_time' => $overdue_time + $time,
            ];
        }else{
            $update = [
                'is_register_member' => 1,
                'is_money_level' => 1,
                'level_status' => 1,
                'inter_reg' => 1,
                'overdue_time' => time() + $time,
            ];
        }
        $res = User::where("uid", $params['user_id'])->update($update);

        return true;
    }





    /**
     * 更新用户信息
     * @param $user
     * @param $uid
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateUserInfo(int $uid, array $user, $userInfo = [])
    {
		if (!$userInfo) {
			$userInfo = $this->dao->get($uid);
			if (!$userInfo) {
				throw new ValidateException('数据不存在');
			}
		}
        $data = [];
        if (isset($user['nickname']) && $user['nickname']) {
            $data['nickname'] = $user['nickname'];
        }
        if (isset($user['headimgurl']) && $user['headimgurl']) {
            $data['avatar'] = $user['headimgurl'];
        }
        if (isset($user['phone']) && $user['phone'] && isset($userInfo['phone']) && !$userInfo['phone']) {
            $data['phone'] = $user['phone'];
        }
        $data['monitor_sanlitun']=$userInfo['monitor_sanlitun']??0;
        $data['last_time'] = time();
        $data['client_type'] = $userInfo['client_type'];
        $data['user_type'] = $userInfo['user_type'];
        $data['last_ip'] = app()->request->ip();
        if(!empty($userInfo['device_token_an'])) $data['device_token_an'] = $userInfo['device_token_an'];
        if(!empty($userInfo['device_token_ios'])) $data['device_token_ios'] = $userInfo['device_token_ios'];
        if(!empty($userInfo['is_app_login'])) $data['is_app_login'] = $userInfo['is_app_login'];

        //永久绑定
        $store_brokergae_binding_status = sys_config('store_brokerage_binding_status', 1);
        $spread_uid = isset($user['code']) && $user['code'] && $user['code'] != $userInfo['uid'] ? $user['code'] : ($user['spread_uid'] ?? 0);
        if ($userInfo['spread_uid'] && $store_brokergae_binding_status == 1) {
            $data['login_type'] = $user['login_type'] ?? $userInfo['login_type'];
        } else {
            //绑定分销关系 = 所有用户
            if (sys_config('brokerage_bindind', 1) == 1) {
                //分销绑定类型为时间段且过期 ｜｜临时
                $store_brokerage_binding_time = sys_config('store_brokerage_binding_time', 30);
                if (!$userInfo['spread_uid'] || $store_brokergae_binding_status == 3 || ($store_brokergae_binding_status == 2 && ($userInfo['spread_time'] + $store_brokerage_binding_time * 24 * 3600) < time())) {
                    $spreadUid = $spread_uid;
                    if ($spreadUid && ($userInfo['uid'] == $spread_uid || $userInfo['uid'] == $this->dao->value(['uid' => $spreadUid], 'spread_uid'))) {
                        $spreadUid = 0;
                    }
                    if ($spreadUid && $this->dao->get((int)$spreadUid)) {
                        $data['spread_uid'] = $spreadUid;
                        $data['spread_time'] = time();
                    }
                }
            }
        }
        if (!$this->dao->update($uid, $data, 'uid')) {
            throw new ValidateException('修改信息失败');
        }
        if (isset($data['spread_uid']) && $data['spread_uid']) {
            event('user.register', [$this->dao->get((int)$userInfo['uid']), false, $spread_uid]);
            //推送消息
//            event('notice.notice', [['spreadUid' => $spreadUid, 'user_type' => $userInfo['user_type'], 'nickname' => $userInfo['nickname']], 'bind_spread_uid']);
        }

        return true;
    }






    /**
     * 发送验证码
     * @param $phone
     * @param $type
     * @param $time
     * @param $ip
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function verify($phone, $type, $time, $ip)
    {
        if ($this->dao->getOne(['account' => $phone,]) && $type == 'register') {
            throw new ValidateException('手机号已注册');
        }
        $default = Config::get('sms.default', 'yihaotong');
        $defaultMaxPhoneCount = Config::get('sms.maxPhoneCount', 10);
        $defaultMaxIpCount = Config::get('sms.maxIpCount', 50);
        $maxPhoneCount = Config::get('sms.stores.' . $default . '.maxPhoneCount', $defaultMaxPhoneCount);
        $maxIpCount = Config::get('sms.stores.' . $default . '.maxIpCount', $defaultMaxIpCount);
        /** @var SmsRecordServices $smsRecord */
        $smsRecord = app()->make(SmsRecordServices::class);
        if ($smsRecord->count(['phone' => $phone, 'add_ip' => $ip, 'time' => 'today']) >= $maxPhoneCount) {
            throw new ValidateException('您今日发送得短信次数已经达到上限');
        }
        if ($smsRecord->count(['add_ip' => $ip, 'time' => 'today']) >= $maxIpCount) {
            throw new ValidateException('此IP今日发送次数已经达到上限');
        }
        if (CacheService::get('code_' . $phone))
            throw new ValidateException($time . '分钟内有效');
        mt_srand();
        $code = rand(100000, 999999);
        $data['code'] = $code;
        $data['time'] = $time;
        $res = SmsJob::dispatch([$phone, $data, 'VERIFICATION_CODE_TIME']);
        if (!$res)
            throw new ValidateException('短信平台验证码发送失败');
        return $code;
    }

    /**
     * H5用户注册
     * @param $account
     * @param $password
     * @param $spread_uid
     * @return User|\think\Model
     */
    public function register($account, $password, $spread_uid, $user_type = 'h5', $share_code='', $is_from=false, $device_token_an='',$device_token_ios='',$monitor_sanlitun=0,$client='')
    {
        if ($this->dao->getOne(['phone' => $account])) {
            throw new ValidateException('用户已存在,请去修改密码');
        }
        $phone = $account;

        /*
           $share_pid = 0;
           $integral = 0;
           $share_ids = [];
           $share_id_count = 0;
           if($is_from){
               if(!empty($share_code)){
                   $code_find = $this->dao->getOne(['share_code' => $share_code]);
                   if(!empty($code_find)){
                       $share_pid = $code_find->uid; //分享者id
                       $integral = $code_find->integral;
                       $share_id_count = $code_find->subordinate_count; //ids数量
                       if(!empty($code_find->subordinate)) $share_ids = explode(',', $code_find->subordinate ?? ''); //ids
                   }
               }
           }
           */


        $data['account'] = $account;
        $data['pwd'] = md5((string)$password);
        $data['phone'] = $phone;
        $data['client_type'] = $client;
        if ($spread_uid && $this->dao->get((int)$spread_uid)) {
            $data['spread_uid'] = $spread_uid;
            $data['spread_time'] = time();
        }

        //------------------------新人礼--------------------------
//        $data['overdue_time'] = time() + 3600 * 24 * 30;
//        $data['is_money_level'] = 1;
//        $data['level_status'] = 1;
//        $data['inter_reg'] = 1;
        //-------------------------------------------------------


        $data['real_name'] = '';
        $data['is_app_login'] = 2;
        $data['birthday'] = 0;
        $data['card_id'] = '';
        $data['mark'] = '';
        $data['addres'] = '';
        $data['user_type'] = $user_type;
        $data['add_time'] = time();
        $data['add_ip'] = app('request')->ip();
        $data['last_time'] = time();
        $data['last_ip'] = app('request')->ip();
        $data['nickname'] = substr(md5($account . time()), 0, 12);
        $data['avatar'] = $data['headimgurl'] = sys_config('h5_avatar');
        $data['city'] = '';
        $data['language'] = '';
        $data['province'] = '';
        $data['country'] = '';
        $data['device_token_an'] = $device_token_an ?? '';
        $data['device_token_ios'] = $device_token_ios ?? '';
        $data['status'] = 1;
        $data['share_code'] = User::generateNonceStr(6);
        $data['pid_share_code'] = $share_code ?? '';
        $data['monitor_sanlitun'] = $monitor_sanlitun;
        if (!$re = $this->dao->save($data)) {
            throw new ValidateException('注册失败');
        } else {
            //用户注册成功事件
            event('user.register', [$this->dao->get((int)$re->uid), true, $spread_uid]);
//
//            $add_sync_user = [
//                "uid" => $re->uid,
//                "account" => $account,
//                "pwd" => password_hash($password, PASSWORD_BCRYPT),
//                "real_name" => '',
//                "avatar" => $data['avatar'],
//                "create_time" => date("Y-m-d H:i:s"),
//                "last_time" => date("Y-m-d H:i:s"),
//                "last_ip" => app('request')->ip(),
//                "promoter_switch" => 0,
//                "user_type" => $user_type,
//                "phone" => $phone,
//                "nickname" => substr($phone, 0, 3) . '****' . substr($phone, 7, 4),
////                "is_svip" => 1,
////                "svip_endtime" => date("Y-m-d H:i:s", $data['overdue_time']),
//            ];
//            RecoveryProduct::syncCreateUser($add_sync_user);

            /*
           if(!empty($share_pid)){
               //分享者人数、积分更新
               array_push($share_ids, $re->uid);
               $subordinate = implode(',', $share_ids);
               $update = [
                   'subordinate' => $subordinate,
                   'integral' => $integral+User::SHARE_NEW_INTEGRAL,
                   'subordinate_count' => $share_id_count+1,
               ];
               User::where("uid", $share_pid)->update($update);

               //分享邀请记录添加
               UserShareInviteLog::addUserShareInvateLog($share_pid,1,User::SHARE_NEW_INTEGRAL, (int)$re->uid);

               //友盟系统消息
               $pushMsgServices = app()->make(PushMsgServices::class);
               $pushMsgServices->umengPushMsg($share_pid, '', 5, User::SHARE_NEW_INTEGRAL);

               $add = [
                   'uid' => $share_pid,
                   'pm' => 1,
                   'title' => '分享新用户注册赠送积分',
                   'category' => 'integral',
                   'type' => 'share_new',
                   'number' => User::SHARE_NEW_INTEGRAL,
                   'balance' => $integral+User::SHARE_NEW_INTEGRAL,
                   'mark' => '分享新用户注册赠送'.User::SHARE_NEW_INTEGRAL.'积分',
                   'add_time' => time(),
               ];
               UserBill::create($add);
           }
           */

            //推送消息
//            event('notice.notice', [['spreadUid' => $spread, 'user_type' => $user_type, 'nickname' => $data['nickname']], 'bind_spread_uid']);
            return $re;
        }
    }

    /**
     * 重置密码
     * @param $account
     * @param $password
     */
    public function reset($account, $password)
    {
        $user = $this->dao->getOne(['phone' => $account]);
        if (!$user) {
            throw new ValidateException('登录失效，请重新登录');
        }
        if (!$this->dao->update($user['uid'], ['pwd' => md5((string)$password)], 'uid')) {
            throw new ValidateException('修改密码失败');
        }
        return true;
    }

    /**
     * 手机号登录
     * @param $phone
     * @param $spread_uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function mobile($phone, $spread_uid, $user_type = 'h5', $device_token_an='', $device_token_ios='', $isApp=0,$share_code,$monitor_sanlitun,$client)
    {
        //数据库查询
        $user = $this->dao->getOne(['phone' => $phone]);
        if (!$user) {
            $user = $this->register($phone, '123456a', $spread_uid, $user_type,$share_code,'',$device_token_an,$device_token_ios,$monitor_sanlitun,$client);
            if (!$user) {
                throw new ValidateException('用户登录失败,无法生成新用户,请稍后再试!');
            }
            /** @var UserServices $userServices */
            $userServices = app()->make(UserServices::class);
            $userServices->incField($user['uid'], 'integral', User::NEW_REGISTER_INTEGRAL);
            $add = [
                'uid' => $user['uid'],
                'pm' => 1,
                'title' => '新用户注册赠送积分',
                'category' => 'integral',
                'type' => 'share_news',
                'number' => User::NEW_REGISTER_INTEGRAL,
                'balance' => User::NEW_REGISTER_INTEGRAL,
                'mark' => '新用户注册赠送'.User::NEW_REGISTER_INTEGRAL.'积分',
                'add_time' => time(),
            ];
            UserBill::create($add);

            /** @var PushMsgServices  $pushMsgServices */
            $pushMsgServices = app()->make(PushMsgServices::class);
            //友盟系统消息
            $pushMsgServices->umengPushMsg((int)$user['uid'], '', 10, (string)User::NEW_REGISTER_INTEGRAL);
            }

        if (!$user->status)
            throw new ValidateException('已被禁止，请联系管理员');

        if(!empty($device_token_an)) $user['device_token_an'] = $device_token_an;
        if(!empty($device_token_ios)) $user['device_token_ios'] = $device_token_ios;
        if(!empty($client)) $user['client_type'] = $client;


        $is_from = false;
        //----------------------------新人礼分享者人数、积分更新--------------------------
        //注册送积分，用户从app登录后
        $is_app_login = 2;
        $share_pid = 0;
        if($isApp){
            $is_app_login = 1;
            $integral = 0;
            $share_ids = [];
            $share_id_count = 0;

            if($user['monitor_sanlitun'] == 1) $is_from = true;
            if($is_from){
                if(!empty($user['spread_uid']) &&  ($user['is_app_login']==2) ){
                    $code_find = $this->dao->getOne(['uid' => $user['spread_uid']]);
                    if(!empty($code_find)){
                        $share_pid = $code_find->uid; //分享者id
                        $integral = $code_find->integral ?? 0;
                        $share_id_count = $code_find->subordinate_count; //ids数量
                        if(!empty($code_find->subordinate)) $share_ids = explode(',', $code_find->subordinate ?? ''); //ids
                    }
                }
            }
        }

        if($is_app_login == 1) $user['is_app_login'] = $is_app_login;

        $uid = (int)$user['uid'];



        $token = $this->createToken($uid, 'api', $user->pwd);
        if ($token) {
			// 用户登录成功事件
			event('user.login', [$uid, app('request')->ip()]);
            //----------------------------分享者人数、积分更新--------------------------
            if(!empty($share_pid)){
                // 设置推广关系
                $this->updateUserInfo($uid, ['spread_uid' => $spread_uid], $user);
                //--------------------------------------------------------------------

                array_push($share_ids, $uid);
                $subordinate = implode(',', $share_ids);
                $update = [
                    'subordinate' => $subordinate,
                    'integral' => $integral+User::SHARE_NEW_INTEGRAL,
                    'subordinate_count' => $share_id_count+1,
                ];
                User::where("uid", $share_pid)->update($update);

                //分享邀请记录添加
                UserShareInviteLog::addUserShareInvateLog($share_pid,1,User::SHARE_NEW_INTEGRAL, $uid);

                $add = [
                    'uid' => $share_pid,
                    'pm' => 1,
                    'title' => '分享新用户注册赠送积分',
                    'category' => 'integral',
                    'type' => 'share_new',
                    'number' => User::SHARE_NEW_INTEGRAL,
                    'balance' => $integral+User::SHARE_NEW_INTEGRAL,
                    'mark' => '分享新用户注册赠送'.User::SHARE_NEW_INTEGRAL.'积分',
                    'add_time' => time(),
                ];
                UserBill::create($add);

				/** @var PushMsgServices  $pushMsgServices */
	            $pushMsgServices = app()->make(PushMsgServices::class);
                //友盟系统消息
                $pushMsgServices->umengPushMsg($share_pid, '', 5, (string)User::SHARE_NEW_INTEGRAL);
            }
            //--------------------------------------------------------------------


            return ['token' => $token['token'], 'expires_time' => $token['params']['exp']];
        } else {
            throw new ValidateException('登录失败');
        }
    }

    /**
     * 切换登录
     * @param $user
     * @param $from
     */
    public function switchAccount($user, $from)
    {
        if ($from === 'h5') {
            $where = [['phone', '=', $user['phone']], ['user_type', '<>', 'h5']];
            $login_type = 'wechat';
        } else {
            //数据库查询
            $where = [['account|phone', '=', $user['phone']], ['user_type', '=', 'h5']];
            $login_type = 'h5';
        }
        $switch_user = $this->dao->getOne($where);
        if (!$switch_user) {
            return app('json')->fail('登录失效,无法切换，请重新登录');
        }
        if (!$switch_user->status) {
            return app('json')->fail('已被禁止，请联系管理员');
        }
        $edit_data = ['login_type' => $login_type];
        if (!$this->dao->update($switch_user['uid'], $edit_data, 'uid')) {
            throw new ValidateException('修改新用户登录类型出错');
        }
		$uid = (int)$switch_user['uid'];
        $token = $this->createToken($uid, 'api', $switch_user['pwd']);
        if ($token) {
			// 用户登录成功事件
			event('user.login', [$uid, app('request')->ip()]);
            return ['token' => $token['token'], 'expires_time' => $token['params']['exp']];
        } else {
            throw new ValidateException('切换失败');
        }
    }

    /**
     * 绑定手机号(静默还没写入用户信息)
     * @param $user
     * @param $phone
     * @param $step
     * @return mixed
     */
    public function bindind_phone($phone, $key = '')
    {
        if (!$key) {
            throw new ValidateException('请刷新页面或者重新授权');
        }
        [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = $createData = CacheService::getTokenBucket($key);
        if (!$createData) {
            throw new ValidateException('请刷新页面或者重新授权');
        }
        $wechatInfo['phone'] = $phone;
        /** @var WechatUserServices $wechatUser */
        $wechatUser = app()->make(WechatUserServices::class);
        //更新用户信息
        $user = $wechatUser->wechatOauthAfter([$openid, $wechatInfo, $spread_uid, $login_type, $userType]);
        $token = $this->createToken((int)$user['uid'], $userType, $user['pwd']);
        if ($token) {
            return [
                'token' => $token['token'],
                'userInfo' => $user,
                'expires_time' => $token['params']['exp'],
            ];
        } else
            return app('json')->fail('获取用户访问token失败!');
    }

    /**
     * 用户绑定手机号
     * @param $user
     * @param $phone
     * @param $step
     * @return mixed
     */
    public function userBindindPhone(int $uid, $phone, $step)
    {
        $userInfo = $this->dao->get($uid);
        if (!$userInfo) {
            throw new ValidateException('登录失效');
        }
        if ($this->dao->getOne(['phone' => $phone])) {
            throw new ValidateException('此手机已经绑定，无法多次绑定！');
        }
        if ($userInfo->phone == $phone) {
            throw new ValidateException('绑定手机号码与现有手机号相同');
        }
        $data = [];
        if ($this->dao->getOne(['account' => $phone, 'phone' => $phone, 'user_type' => 'h5'])) {
            if (!$step) return ['msg' => 'H5已有账号是否绑定此账号上', 'data' => ['is_bind' => 1]];
        } else {
            $data['account'] = $phone;
        }
        $data['phone'] = $phone;
        if ($this->dao->update($userInfo['uid'], $data, 'uid') || $userInfo->phone == $phone)
            return ['msg' => '绑定成功', 'data' => []];
        else
            throw new ValidateException('绑定失败');
    }

    /**
     * 用户绑定手机号
     * @param $user
     * @param $phone
     * @param $step
     * @return mixed
     */
    public function updateBindindPhone(int $uid, $phone)
    {
        $userInfo = $this->dao->get($uid);
        if (!$userInfo) {
            throw new ValidateException('登录失败，请重新登录');
        }
        if ($userInfo->phone == $phone) {
            throw new ValidateException('新手机号和原手机号相同，无需修改');
        }
        if ($this->dao->getOne([['phone', '=', $phone]])) {
            throw new ValidateException('此手机已经注册');
        }
        $data = [];
        $data['phone'] = $phone;
        if ($this->dao->update($userInfo['uid'], $data, 'uid'))
            return ['msg' => '修改成功', 'data' => []];
        else
            throw new ValidateException('修改失败');
    }
}
